package com.example.httprequestdemos;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;


public class PostDemo{
    /**
     * 处理post请求
     * @param urlStr 请求url
     * @param data 请求体数据
     * @param properties 请求头参数
     * @return
     */
    public static String post(String urlStr, JSONObject data, Map<String, String> properties){
        try {
            //log.info("请求url={}", urlStr);
            //log.info("请求体数据data={}", data.toJSONString());
            //log.info("请求头参数properties={}", properties);
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setDoInput(true); // 设置可输入
            connection.setDoOutput(true); // 设置该连接是可以输出的
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
//            for (String key:properties.keySet()){
//                connection.setRequestProperty(key, properties.get(key));
//            }

            PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
            pw.write(data.toJSONString());
            pw.flush();
            pw.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line = null;
            StringBuilder result = new StringBuilder();
            while ((line = br.readLine()) != null) { // 读取数据
                result.append(line + "\n");
            }
            connection.disconnect();
            return result.toString();
        } catch (Exception e) {
          ///  log.error("post请求失败");
            System.out.println(e);
            return "post请求失败！";
        }
    }

}
